package com.game.state;


import javax.microedition.khronos.opengles.GL10;

import object.obj2D.graphics.TexSquare;
import object.obj2D.graphics.Texture;
import system.Device;
import system.Graphics;

import com.game.GamePlay;
import com.game.R;

public class ShowLogo extends State {
	
	private int m_fSrcWidth;
	private int m_fSrcHeight;
	private GL10 gl;
	private Texture m_logoTexture;
	private int m_iLogoTexID;
	private TexSquare m_logoSquare;
	private int m_iLogoWidth = 272;
	private int m_iLogoHeight = 187;
	
	private static final int SHOW_LOGO_TIME = 2000;
	private long m_fShowLogoStartTime;
	private long m_fShowLogoEndTime;
	
	private boolean m_isUpdateAlpha = true;
	private float m_alpha = 0.0f;
	private long UPDATE_ALPHA_TIME = 100;
	private long m_lastUpdateAlpha;

	public void Destroy() {
		m_logoSquare = null;
		m_logoTexture = null;
	}

	public void Init() {
		gl = Graphics.GetGraphics();
		m_fSrcWidth = Device.GetWidth();
		m_fSrcHeight = Device.GetHeight();
		
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		
		float w = m_fSrcWidth/2;
		float h = m_fSrcHeight/2;
		gl.glOrthof(-w, w, -h, h, -1.0f, 1.0f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glPushMatrix();
		loadTexture();
		
		m_fShowLogoStartTime = System.nanoTime();
		m_lastUpdateAlpha = m_fShowLogoStartTime;
	}
	
	private void loadTexture()
	{
		m_logoTexture = new Texture();
		m_iLogoTexID = m_logoTexture.initTexture(R.drawable.gameloftlogo);
		m_logoSquare = new TexSquare(m_iLogoWidth, m_iLogoHeight);
	}

	public void Render() {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		
		gl.glColor4f(1.0f, 1.0f, 1.0f, m_alpha);
		
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glPushMatrix();
		
		m_logoTexture.loadTexture(m_iLogoTexID);
		m_logoSquare.Render();
		
		gl.glPopMatrix();
	}
	
	public void Update(GamePlay gamePlay) {
		if(m_isUpdateAlpha && (System.nanoTime() - m_lastUpdateAlpha)/1000000 > UPDATE_ALPHA_TIME)
		{
			m_alpha += 0.1f;
			m_lastUpdateAlpha = System.nanoTime();
			if(m_alpha >= 1.0f) m_isUpdateAlpha = false;
			
		}
		
		m_fShowLogoEndTime = System.nanoTime();
		if((m_fShowLogoEndTime - m_fShowLogoStartTime)/1000000 > SHOW_LOGO_TIME)
		{
			gamePlay.SwitchState(GameState.AskForSounds);
		}
		
		super.Update(gamePlay);
	}

	@Override
	public void ProcessKeyboard(GamePlay gamePlay) {
		// TODO Auto-generated method stub
		
	}
}
